package com.sjf.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author <huangtang>
 * @since 2022/4/25 15:02
 **/
@ControllerAdvice(annotations = { RestController.class })
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error("系统异常:{}", e.getMessage ());
        String msg = e.getMessage ();
        if(e.getMessage ().contains ("Duplicate entry")) {
            String[] split = e.getMessage ().split (" ");
            msg = split[2]+"  已存在";
        }
        return Result.error (msg);
    }

    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException e) {
        log.error("业务异常:{}", e.getMessage ());
        return Result.error (e.getMessage ());
    }

}
